package cn.yaxma.xmpp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Created by Yaxma on 2016/11/3.
 * Email：2678503498@qq.com
 */

public class ChatActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private EditText content_edt;
    private Button send_btn;
    private ChatAdapter mChatAdapter;

    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        initView();

        LoginActivity.setMessageCallback(new LoginActivity.MessageCallback() {
            @Override public void receiveMsg(String msg) {
                ChatMessage chatMessage = new ChatMessage(ChatMessage.Direction.RECEIVE);
                chatMessage.setMsg(msg);
                mChatAdapter.addMessage(chatMessage);
                mRecyclerView.smoothScrollToPosition(mChatAdapter.getItemCount());
            }
        });
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        content_edt = (EditText) findViewById(R.id.content_edt);
        send_btn = (Button) findViewById(R.id.send_btn);

        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                String content = content_edt.getText().toString();
                XMPPService.getConnection().sendMessage("222", content);
                content_edt.setText("");
                ChatMessage chatMessage = new ChatMessage(ChatMessage.Direction.SEND);
                chatMessage.setMsg(content);
                mChatAdapter.addMessage(chatMessage);
                mRecyclerView.smoothScrollToPosition(mChatAdapter.getItemCount());
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mChatAdapter = new ChatAdapter(this);
        mRecyclerView.setAdapter(mChatAdapter);
    }
}
